<template>
  <div class="'box">
    <el-dialog :title="`${title}`" :visible.sync="showDialog" width="50%" @close="btnCancel">
      <!-- 表单 -->
      <el-form ref="form" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" style="width:90%" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" style="width:90%" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description" style="width:90%" />
        </el-form-item>
        <el-form-item label="开启">
          <el-switch
            v-model="formData.enVisible"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click=" showDialog = false">取消</el-button>
        <el-button type="primary" @click="btnOk">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addPermissionApi, infoPermissionApi, updatePermissionApi } from '@/api/permission'
export default {
  data() {
    return {
      // 表单数据
      formData: {
        name: '',
        code: '',
        description: '',
        type: '',
        pid: '',
        enVisible: ''
      },
      // 校验规则
      formRules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
      },
      // 弹框控制变量
      showDialog: false
    }
  },
  computed: {
    // 标题优化
    title() {
      return this.formData.id ? '修改权限' : '添加权限'
    }
  },
  methods: {
    // 提交
    async btnOk() {
      // 表单校验
      await this.$refs.form.validate()
      // 发送请求
      this.formData.id ? await updatePermissionApi(this.formData) : await addPermissionApi(this.formData)
      // 提示消息
      this.$message.success('操作成功')
      // 关闭弹框
      this.showDialog = false
      // 通知父组件更新
      this.$emit('updateList')
    },
    // 取消
    btnCancel() {
      // 清除校验
      this.$refs.form.clearValidate()
      // 重置表单
      this.formData = {
        name: '',
        code: '',
        description: '',
        type: '',
        pid: '',
        enVisible: ''
      }
    },
    // 编辑回显
    async editRow(id) {
      // 发送请求，根据获取id获取详情数据
      const res = await infoPermissionApi(id)
      // 赋值变量
      this.formData = res
      // 打开弹框
      this.showDialog = true
    }
  }
}
</script>

<style>

</style>
